﻿using System;
using System.Web.UI.WebControls;

namespace MyOrganizer.Pages
{
    public partial class Movies : System.Web.UI.Page
    {
        private MyOrganizerModel.BusinessModel Bl = null;
        private MyOrganizerModel.Database.Movies Film = null;
        private int UserId { get { return Int32.Parse(Session["UserId"].ToString()); } }

        protected void Page_Load(object sender, EventArgs e)
        {
            Bl = MyOrganizerModel.BusinessModel.GetInstance;
            LoadData();
        }

        protected void rptData_ItemCommand(object source, RepeaterCommandEventArgs e)
        {
            switch (e.CommandName.ToString())
            {
                case "Edit":
                    Film = Bl.GetMovieByMovieId(Int32.Parse(e.CommandArgument.ToString()));
                    txtId.Text = Film.MovieId.ToString();
                    txtName.Text = Film.Name;
                    txtType.Text = Film.Type;
                    txtViewedDate.Text = Film.ViewedDate;
                    txtScore.Text = Film.Score;
                    mdlPopUp.Show();
                    break;

                case "Delete":
                    Bl.DeleteMovie(Int32.Parse(e.CommandArgument.ToString()));
                    LoadData();
                    break;

                default:
                    break;
            }
        }

        protected void lnkSave_Click(object sender, EventArgs e)
        {
            Film = new MyOrganizerModel.Database.Movies();
            if (txtId.Text.Equals(string.Empty))
            {
                Film.UserId = UserId;
                Film.Name = txtName.Text;
                Film.Type = txtType.Text;
                Film.ViewedDate = txtViewedDate.Text;
                Film.Score = txtScore.Text;
                Bl.AddMovie(Film);
            }
            else
            {
                Film.MovieId = Int32.Parse(txtId.Text);
                Film.UserId = UserId;
                Film.Name = txtName.Text;
                Film.Type = txtType.Text;
                Film.ViewedDate = txtViewedDate.Text;
                Film.Score = txtScore.Text;
                Bl.UpdateMovie(Film);
            }
            LoadData();
        }

        protected void lnkAdd_Click(object sender, EventArgs e)
        {
            TextBox txt = default(TextBox);
            foreach (var ctrl in pnlPopUp.Controls)
            {
                if (object.ReferenceEquals(ctrl.GetType(), typeof(TextBox)))
                {
                    txt = (TextBox)ctrl;
                    txt.Text = String.Empty;
                }
            }
            mdlPopUp.Show();
        }

        private void LoadData()
        {
            rptData.DataSource = Bl.GetMovies();
            rptData.DataBind();
        }
    }
}